<template>
  <div class="min-h-screen bg-gray-50">
    <div class="px-4 pt-4">
      <nav class="text-sm text-gray-500 flex items-center space-x-2">
        <NuxtLink to="/" class="text-blue-600 hover:underline">首页</NuxtLink>
        <span>/</span>
        <span class="text-gray-700">签约记录</span>
      </nav>
    </div>
    <!-- 页面标题 -->
    <div class="text-center py-6">
      <h1 class="text-xl font-medium text-gray-900">签约记录</h1>
    </div>

    <div class="p-4">
      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-8">
        <div class="text-gray-500">加载中...</div>
      </div>

      <!-- 记录列表 -->
      <div v-else-if="contracts.length > 0" class="space-y-4">
        <div
          v-for="contract in contracts"
          :key="contract.id"
          class="bg-white rounded-lg p-4 shadow-sm"
        >
          <!-- 基本信息 -->
          <div class="flex justify-between items-start mb-3">
            <div>
              <h3 class="text-base font-medium text-gray-900">{{ contract.taskName }}</h3>
              <p class="text-sm text-gray-600 mt-1">任务ID: {{ contract.taskId }}</p>
            </div>
            <div class="text-right">
              <div
                class="px-2 py-1 rounded-full text-xs font-medium"
                :class="getStatusClass(contract.status)"
              >
                {{ getStatusText(contract.status) }}
              </div>
              <p class="text-xs text-gray-500 mt-1">{{ contract.createdAt }}</p>
            </div>
          </div>

          <!-- 详细信息 -->
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-600">服务类型:</span>
              <span class="text-gray-900">{{ contract.serviceType }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">计费标准:</span>
              <span class="text-blue-600 font-medium">
                {{ contract.minFee.toLocaleString() }} - {{ contract.maxFee.toLocaleString() }}元/次
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">工作地点:</span>
              <span class="text-gray-900">{{ contract.workLocation }}</span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">任务周期:</span>
              <span class="text-gray-900">{{ contract.startTime }} 至 {{ contract.endTime }}</span>
            </div>
          </div>

          <!-- 审核备注 -->
          <div v-if="contract.reviewNote" class="mt-3 p-3 bg-gray-50 rounded-md">
            <div class="flex items-start justify-between gap-3">
              <p class="text-sm text-gray-700 flex-1">
                <span class="font-medium">审核备注:</span> {{ contract.reviewNote }}
              </p>
              <button
                v-if="contract.status === 'approved'"
                class="px-3 py-1 text-sm bg-blue-500 text-white rounded hover:bg-blue-600 transition"
                @click="handleDownload(contract.id)"
              >
                下载合同
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="text-center py-12">
        <div class="text-gray-400 text-4xl mb-4">📋</div>
        <div class="text-gray-500 mb-4">暂无签约记录</div>
        <button
          @click="goToProfile"
          class="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
        >
          返回首页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useApi } from '~/utils/apiConfig'

const loading = ref(true)
const contracts = ref([])

// API 实例
const api = useApi('freelancer')

/**
 * 获取状态对应的CSS类
 */
const getStatusClass = (status) => {
  const classMap = {
    'pending': 'bg-yellow-100 text-yellow-800',
    'approved': 'bg-green-100 text-green-800',
    'rejected': 'bg-red-100 text-red-800',
    'working': 'bg-blue-100 text-blue-800',
    'completed': 'bg-gray-100 text-gray-800'
  }
  return classMap[status] || 'bg-gray-100 text-gray-800'
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  const textMap = {
    'pending': '已报待审',
    'approved': '审核通过',
    'rejected': '审核未通过',
    'working': '工作中',
    'completed': '已完成'
  }
  return textMap[status] || status
}

/**
 * 获取签约记录
 */
const fetchContracts = async () => {
  loading.value = true
  try {
    const response = await api.get('/contracts')

    if (response.code === 0) {
      contracts.value = response.data || []
    } else {
      throw new Error(response.message || '获取签约记录失败')
    }
  } catch (error) {
    console.error('获取签约记录失败:', error)
    contracts.value = []
  } finally {
    loading.value = false
  }
}

/**
 * 返回首页
 */
const goToProfile = () => {
  navigateTo('/profile')
}

const notifySuccess = (msg) => {
  if (window?.toast) {
    window.toast.success(msg)
  } else {
    alert(msg)
  }
}

const notifyError = (msg) => {
  if (window?.toast) {
    window.toast.error(msg)
  } else {
    alert(msg)
  }
}

const handleDownload = async (contractId) => {
  try {
    const response = await api.get(`/contracts/${contractId}/download`)

    if (response?.data?.download_url) {
      window.open(response.data.download_url, '_blank')
      notifySuccess('合同打开成功')
      return
    }

    if (response instanceof Blob) {
      const blob = new Blob([response], { type: 'application/pdf' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `contract-${contractId}.pdf`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      notifySuccess('合同开始下载')
      return
    }

    notifyError('合同下载失败，请稍后重试')
  } catch (error) {
    console.error('下载合同失败:', error)
    notifyError('下载合同失败，请稍后重试')
  }
}

// 页面初始化
onMounted(() => {
  fetchContracts()
})
</script>
